<template>
	<view class="register">
		<view class="title" style="text-align: center;">
			<text>注册</text>
		</view>
		<view class="content">
			<uni-forms ref="regForm" :model="regFormData" :rules="rules" validateTrigger="blur">
				<uni-forms-item name="username">
					<uni-easyinput v-model="regFormData.username" prefix-icon="person" placeholder="请输入用户名" />
				</uni-forms-item>
				<uni-forms-item name="password">
					<uni-easyinput type="password" v-model="regFormData.password" placeholder="请输入密码" />
				</uni-forms-item>
				<uni-forms-item name="mobilePhoneNumber">
					<uni-easyinput v-model="regFormData.mobilePhoneNumber" prefix-icon="person" placeholder="请输入手机号码" />
				</uni-forms-item>
			</uni-forms>
			<button class="button" type="primary" @click="register">注册</button>
		</view>
		<view class="login-prompt">
			<navigator style="text-align: center; font-size: 40px;" url="/pages/login/login">已有账号？去登录</navigator>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
	} from '@dcloudio/uni-app'
	const regFormData = ref({
		username: 'admin4',
		password: '123456',
		mobilePhoneNumber: '1875293225239',
	});

	const rules = {
		username: [{
			required: true,
			errorMessage: '请输入用户名'
		}],
		password: [{
			required: true,
			errorMessage: '请输入密码'
		}],
		mobilePhoneNumber: [{
			required: true,
			errorMessage: '请输入手机号码'
		}]
	};

	const regForm = ref(null);

	function register() {
		// 这里假设您已经关闭了二次密码验证，因此我们只需要验证密码一次
		if (regForm.value.validate()) { // 确保表单验证通过
			uni.request({
				url: 'https://v7hs8eni.lc-cn-n1-shared.com/1.1/users', // 确保这是您的注册API地址
				method: 'POST',
				data: regFormData.value
			}).then((res) => {
				console.log(res)
				if (res.data.statusCode = 201) { // 假设后端返回的statusCode为200表示注册成功
					uni.showToast({
						title: '注册成功',
						icon: 'success'
					});
					setTimeout(() => { // 使用setTimeout来延迟跳转，以便用户能看到提示信息
						uni.navigateTo({
							url: "/pages/login/login" // 跳转到登录页面
						});
					}, 1500); // 延迟1.5秒
				} else {
					uni.showToast({
						title: '注册失败: ' + res.data.error,
						icon: 'none'
					});
				}
			}).catch((err) => {
				console.error('注册失败', err);
				uni.showToast({
					title: '注册失败',
					icon: 'none'
				});
			});
		} else {
			uni.showToast({
				title: '表单验证未通过，请检查输入',
				icon: 'none'
			});
		}
	}
</script>

<style scoped>
	.register {
		border: 1px solid white;
		position: relative;
	}

	.register.title {
		margin-top: 70px;
	}

	.register.title image:nth-child(1) {
		height: 50px;
	}

	.register.title image:nth-child(2) {
		height: 30px;
	}

	.register.content {
		margin: 10px 20px;
	}

	.register.login {
		position: absolute;
		width: 100vw;
		text-align: center;
		color: #007aff;
		bottom: 20px;
		font-size: 20rpx;
	}
</style>